<template>
  <div class="pd-20">
    <el-input v-model="searchCondition"
              placeholder="请输入检测项目名称"
              class="w-200"
              clearable
              @clear="query" />
    <el-button type="primary"
               @click="query">查 询</el-button>
    <el-button type="primary"
               @click="editData(null)">新 增</el-button>
    <Table border
           stripe
           :columns="titles"
           :data="dataList"
           class="mt-20">
      <template slot-scope="{row,index}"
                slot="action">
        <span @click="editData(row)">编辑</span>
        <span @click="configInstrument(row)">配置</span>
        <span @click="deleteData(row)">删除</span>
        <span @click="codeConfig(row)">收费编码配置</span>
      </template>
    </Table>
    <page @on-change="pageChange"
          :total="totals"
          ref="page"
          show-total></page>

    <Modal v-model="editModal"
           title="编辑检测项目"
           :loading="loading"
           width="90%"
           @on-ok="saveData"
           @on-cancel="oncancel"
           footer-hide>
      <div>
        <Form :model="editDevice"
              label-position="right"
              :label-width="120"
              ref="formValidateRef"
              :rules="formValidateRules">
          <FormItem label="图标:"
                    prop="imageUrl">
            <img v-if="editDevice.imageUrl"
                 :src="editDevice.imageUrl"
                 width="64px"
                 height="64px"
                 style="border-radius: 5%" />
            <Upload :action="fileUploadAction"
                    :max-size='fileMaxSize'
                    :show-upload-list="false"
                    :on-exceeded-size="showError"
                    :on-success="itemUploadSuccess">
              <Button icon="ios-cloud-upload-outline">头像上传</Button>
            </Upload>
          </FormItem>
          <FormItem label="检测项目名称:"
                    prop="name">
            <el-input v-model="editDevice.name"
                      type="text"
                      class="w-200"
                      placeholder="请输入检测项目名称" />
          </FormItem>
          <FormItem label="中文名称:"
                    prop="deviceZhName">
            <el-input v-model="editDevice.deviceZhName"
                      type="text"
                      class="w-200"
                      placeholder="请输入中文名称" />
          </FormItem>
          <FormItem label="英文名称:"
                    prop="deviceEnName">
            <el-input v-model="editDevice.deviceEnName"
                      type="text"
                      class="w-200"
                      placeholder="请输入英文名称" />
          </FormItem>
          <FormItem label="是否空腹:"
                    prop="limosis">
            <RadioGroup v-model="editDevice.limosis">
              <Radio :label="0">
                <span>否</span>
              </Radio>
              <Radio :label="1">
                <span>是</span>
              </Radio>
            </RadioGroup>
          </FormItem>

          <FormItem label="手动填写:" class="is-required">
            <RadioGroup v-model="editDevice.supportManual">
              <Radio :label="0">
                <span>否</span>
              </Radio>
              <Radio :label="1">
                <span>是</span>
              </Radio>
            </RadioGroup>
          </FormItem>


          <FormItem label="参考值:">
            <el-input v-model="editDevice.reference"
                      type="textarea"
                      style="width: 360px"
                      placeholder="请输入参考值" />
          </FormItem>

          <FormItem label="临床意义：">
            <div style="position: relative;z-index: 1; max-height:707px;height:707px;">
              <vue-neditor-wrap :destroy="true"
                                v-model="editDevice.clinicalSignificance"
                                :config="myConfig"></vue-neditor-wrap>

            </div>
          </FormItem>
<!--          <FormItem label="知识点：">-->
<!--            <div style="position: relative;z-index: 1; max-height:707px;height:707px;">-->
<!--              <vue-neditor-wrap :destroy="true"-->
<!--                                v-model="editDevice.knowledge"-->
<!--                                :config="myConfig"></vue-neditor-wrap>-->

<!--            </div>-->
<!--          </FormItem>-->
        </Form>
        <p align="center">
          <el-button plain
                     @click="oncancel">取 消</el-button>
          <el-button type="primary"
                     @click="saveData">保 存</el-button>
        </p>
      </div>
    </Modal>

    <Modal v-model="configApparatus"
           title="配置检测仪器"
           width="80%">
      <div>
        <Form :model="configModel"
              :label-width="80">
          <FormItem label="头像">
            <img :src="configModel.imageUrl"
                 width="64px"
                 height="64px"
                 style="border-radius: 5%" />
          </FormItem>
          <FormItem label="名字">
            <el-input v-model="configModel.name"
                      placeholder="请输入名字"
                      disabled></el-input>
          </FormItem>
        </Form>

        <el-table border
                  stripe
                  :data="apparatusList"
                  class="mt-20">
          <el-table-column prop="imageUrl"
                           label="仪器图标">
            <template slot-scope="scope">
              <img :src="scope.row.imageUrl"
                   width="60"
                   height="60">
            </template>
          </el-table-column>
          <el-table-column prop="name"
                           label="仪器名称"></el-table-column>

          <el-table-column prop="factory"
                           label="厂商"></el-table-column>
          <el-table-column prop="machineModel"
                           label="型号"></el-table-column>
          <el-table-column prop="sampleName"
                           label="支持样本">
            <template slot-scope="scoped">
              <el-select multiple
                         value-key="name"
                         v-model="scoped.row.sampleName"
                         @change="changeStripSampleList">
                <el-option v-for="item in scoped.row.testStripSampleList"
                           :key="item.id"
                           :value="item.name"
                           :label="item.name"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="operateVideoUrl"
                           label="视频地址"
                           align="center"
                           width="500px">
            <template slot-scope="scope">
              <a :href="scope.row.operateVideoUrl"
                 target="_blank">{{scope.row.operateVideoUrl}}</a>
              <el-upload class="avatar-uploader"
                         ref="upload"
                         :action="fileUploadVideoAction"
                         :on-progress="(event, file, fileList) => uploadVideoProcess(event, file, fileList, scope.$index)"
                         :on-success="(response, file, fileList) => uploadVideoSuccess(response, file, fileList, scope.$index)"
                         :before-upload="beforeUploadVideo"
                         :show-file-list="false">
                <!-- :disabled="scope.row.optType === 1" -->
                <!-- :data="{videoIndex: scope.row.id}" -->
                <video v-if="scope.row.operateVideoUrl !='' && !scope.row.videoFlag"
                       :src="scope.row.operateVideoUrl"
                       class="avatar video-avatar"
                       controls="controls">
                  您的浏览器不支持视频播放
                </video>
                <p :class="{ 'mt-20': scope.row.operateVideoUrl}">
                  <el-button size="small"
                             type="primary"
                             @click="videoIndex = scope.row.id">
                    <label v-if="scope.row.optType === 0">点击上传</label>
                    <label v-else>重新上传</label>
                  </el-button>
                </p>
                <el-progress v-if="scope.row.videoFlag == true"
                             type="circle"
                             :percentage="scope.row.videoUploadPercent"
                             class="mt-20"></el-progress>

              </el-upload>

            </template>
          </el-table-column>
          <el-table-column prop="option"
                           label="操作"
                           align="center"
                           width="200px">
            <template slot-scope="scope">
              <el-button type="primary"
                         v-if="scope.row.optType === 0"
                         @click="optionDeviceApparatus(scope.row)">新 增</el-button>
              <el-button type="primary"
                         v-if="scope.row.optType === 1"
                         @click="saveDeviceApparatus(scope.row)">保 存</el-button>
              <el-button type="danger"
                         v-if="scope.row.optType === 1"
                         @click="optionDeviceApparatus(scope.row)">删 除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </div>
    </Modal>
    <!-- 收费编码配置 -->
    <code-config v-if="isCodeConfigShow"
                 :visible.sync="isCodeConfigShow"
                 :codeConfigInfo="codeConfigInfo"></code-config>
    <el-dialog title="检测分类图标"
               center
               :visible.sync="imageModal"
               width="30%">
      <img :src="imageUrl"
           style="width:100%;height:100%">
      <span slot="footer">
        <el-button type="primary"
                   @click="imageModal = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import codeConfig from './codeConfig.vue'
  import VueNeditorWrap from 'vue-neditor-wrap'
  export default {
    name: "detectItemList",
    data () {
      return {
        imageModal: false,
        imageUrl: null,
        myConfig: {
          // 你的UEditor资源存放的路径,相对于打包后的index.html
          UEDITOR_HOME_URL: this.api.uEditorHomeUrl,
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: '418',
          // 初始容器宽度
          initialFrameWidth: '100%',
          // 关闭自动保存
          enableAutoSave: false,
          scaleEnabled: true
        },
        testStripSampleList: [],
        testStripSampleIds: [],
        searchCondition: '',
        fileUploadAction: this.api.file.upload,
        fileUploadVideoAction: this.api.file.upload,
        currentPage: 1,
        totals: 0,
        fileMaxSize: 1024 * 50,
        pageSize: 10,
        editModal: false,
        configApparatus: false,
        configModel: {},
        loading: false,
        editDevice: {
          id: null,
          name: "",
          imageUrl: "",
          deviceZhName: "",
          deviceEnName: "",
          limosis: 0, // 是否空腹
          testStripSampleIds: [],
          clinicalSignificance: '',
          supportManual:0,
          // knowledge: '', // 知识点
        },
        titles: [
          {
            title: '检测项目名称',
            key: 'name'
          },
          {
            title: '检测分类图标',
            key: 'imageUrl',
            width: 200,
            render: (h, params) => {
              return h('div', [
                h('img', {
                  attrs: {
                    src: params.row.imageUrl
                  },
                  style: {
                    width: '60px',
                    height: '60px',
                    'border-radius': '50%'
                  },
                  on: {
                    click: (event) => {
                      this.showBigImage(params.row.imageUrl);
                    }
                  }
                }),
              ]);
            }
          },
          {
            title: '中文名称',
            key: 'deviceZhName'
          },
          {
            title: '英文名称',
            key: 'deviceEnName'
          },
          {
            title: '创建时间',
            key: 'createTime',
            render: (h, params) => {
              return h('span',
                this.commonFunction.timestampFormat(new Date(params.row.createTime), 'yyyy-MM-dd hh:mm:ss'));
            }
          },
          {
            title: '操作',
            slot: 'action',
            align: 'center',
            width: 250
          }
        ],
        dataList: [],
        apparatusList: [],
        isCodeConfigShow: false,
        codeConfigInfo: {}, // 收费编码配置信息
        operateVideoUrl: '',
        videoFlag: false,
        // 是否显示进度条
        videoUploadPercent: 0,
        // 进度条的进度，
        isShowUploadVideo: false,
        videoIndex: null,
        formValidateRules: {
          imageUrl: [
            { required: true, message: '请上传图标', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入检测项目名称', trigger: 'blur' }
          ],
          deviceZhName: [
            { required: true, message: '请输入检测项目名称', trigger: 'blur' }
          ],
          deviceEnName: [
            { required: true, message: '请输入英文名称', trigger: 'blur' }
          ]
        },
        configParams: []
      }
    },
    created () {
      this.getList();
    },
    methods: {
      showBigImage (url) {
        this.imageUrl = url;
        this.imageModal = true;
      },
      oncancel () {
        this.testStripSampleIds = [];
        this.editModal = false;
      },
      //试纸样本列表
      testStripSamplegetAll () {
        this.post(this.api.cooperationHospital.testStripSamplegetAll).then(res => {
          if (res.data.code === '200') {
            this.testStripSampleList = res.data.object;
          }
        });
      },
      query () {
        this.currentPage = 1;
        this.getList();
      },

      getList () {
        let param = {
          name: this.searchCondition,
          pageSize: this.pageSize,
          pageIndex: this.currentPage - 1
        };
        this.post(this.api.deviceList.url, param).then((res) => {
          if (res.data.code === '200') {
            this.dataList = res.data.object;
            this.totals = res.data.totalNum;
          }
        });
      },
      showError (file, fileList) {
        this.$Notice.warning({
          title: '文件大小超限',
          desc: '文件  ' + file.name + ' 太大，上传文件大小不能超过50M.'
        });
      },
      pageChange (page) {
        this.currentPage = page;
        this.getList();
      },
      // 配置、 回显检测仪器
      configInstrument (row) {
        this.configApparatus = true;
        this.configModel = row;
        this.testStripSamplegetAll();
        this.post(this.api.apparatus.getAllApparatusList, { deviceId: row.id }).then((res) => {
          if (res.data.code === '200') {
            let resData = res.data.object;
            resData.forEach((item, index) => {
              if (item.sampleName && item.sampleName.indexOf(',') != -1) {
                let str = item.sampleName.split(',');
                item.sampleName = str;
              } else {
                let arr = []
                if (item.sampleName !== '') {
                  arr.push(item.sampleName);
                  item.sampleName = arr;
                } else {
                  item.sampleName = arr;
                }
              }
              if (item.operateVideoUrl) {
                item.videoFlag = false;
                item.videoUploadPercent = 100;
              } else {
                item.videoFlag = false;
                item.videoUploadPercent = 0;
                item.operateVideoUrl = ''
              }
            })
            this.apparatusList = resData;
            this.apparatusList.forEach(item => {
              item['testStripSampleList'] = this.testStripSampleList;
            });

          }
        });
      },
      clearTextArea (field, text) {
        if (field) {
          console.log(field === text)
          if (field === text) {
            field = '';
          } else {
            field = field;
          }
        } else {
          console.log(2)
          if (field === text) {
            field = '';
          } else {
            field = field;
          }
        }
        return field;
      },
      // 回显 编辑检测项目
      editData (row) {
        this.editModal = true;
        // this.testStripSamplegetAll();
        if (row) {
          this.post(this.api.device.getDetail, { id: row.id }).then((res) => {
            if (res.data.code === '200') {
              let resData = res.data.object;
              // this.clearTextArea(resData.clinicalSignificance, '<p>Vue + NEditor + v-model双向绑定</p>');
              // this.clearTextArea(resData.knowledge, '<p>Vue + NEditor + v-model双向绑定</p>');
              if (resData.clinicalSignificance) {
                if (resData.clinicalSignificance === '<p>Vue + NEditor + v-model双向绑定</p>') {
                  resData.clinicalSignificance = '';
                } else {
                  resData.clinicalSignificance = resData.clinicalSignificance;
                }
              } else {
                resData.clinicalSignificance = '';
              }
              // if (resData.knowledge) {
              //   if (resData.knowledge === '<p>Vue + NEditor + v-model双向绑定</p>') {
              //     resData.knowledge = '';
              //   } else {
              //     resData.knowledge = resData.knowledge;
              //   }
              // } else {
              //   resData.knowledge = '';
              // }

              this.editDevice = resData;
              this.editDevice.testStripSampleDtos.forEach(ele => {
                this.testStripSampleIds.push(ele.id)
              })
            }
          });
        } else {
          this.editDevice = {
            id: null,
            name: '',
            imageUrl: '',
            deviceZhName: '',
            deviceEnName: '',
            testStripSampleIds: [],
            clinicalSignificance: '',
            supportManual: 0,
            // knowledge: '', // 知识点
          }
        }

      },
      itemUploadSuccess (obj) {
        if (obj.code === '200') {
          this.editDevice.imageUrl = obj.object[0];
          this.$message.success("上传成功");
        } else {
          this.$message.error("上传失败");
        }
      },
      // 删除
      deleteData (row) {
        this.$confirm('确认删除？')
          .then(_ => {
            this.post(this.api.device.delDevice, { "id": row.id }).then((res) => {
              if (res.data.code === '200') {
                this.$message.success("删除成功");
                this.getList();
              }
            });
          })
          .catch(_ => { });
      },
      codeConfig (row) {
        this.isCodeConfigShow = true;
        this.codeConfigInfo = row;
      },

      // 保存
      saveData () {
        this.$refs.formValidateRef.validate((valid) => {
          if (valid) {
            if (!this.editDevice.testStripSampleIds) {
              this.editDevice.testStripSampleIds = [];
            }
            this.editDevice.testStripSampleDtos = [];
            this.testStripSampleIds.forEach(ele => {
              let op = {};
              op.id = ele;
              this.editDevice.testStripSampleDtos.push(op);
            })
            this.post(this.api.device.editDevice, this.editDevice).then((res) => {
              if (res.data.code === '200') {
                this.editModal = false;
                this.$message.success('保存成功!');
                this.testStripSampleIds = [];
                this.getList();
              }
            });

          }
        })
      },
      // 新增、删除-配置检测仪器
      optionDeviceApparatus (row) {
        this.videoIndex = row.id;
        let param = {
          deviceId: this.configModel.id,
          goodsTypeId: row.id,
          optType: row.optType,
          operateVideoUrl: row.operateVideoUrl,
          sampleName: row.sampleName.join(','),
        };
        this.post(this.api.apparatus.updateDeviceApparatus, param).then((res) => {
          if (res.data.code === '200') {
            this.$message.success('操作成功!');
            this.configInstrument(this.configModel);
          }
        });
      },
      changeStripSampleList (item) {
        this.configParams = item;
      },
      // 保存-配置检测仪器
      saveDeviceApparatus (row) {
        this.videoIndex = row.id;
        let param = {
          sampleName: this.configParams.join(','),
          id: row.deviceGoodsTypeId,
          operateVideoUrl: row.operateVideoUrl
        };
        this.post(this.api.apparatus.editDeviceApparatus, param).then((res) => {
          if (res.data.code === '200') {
            this.$message.success('保存成功');
          }
        });
      },

      // 上传前回调
      beforeUploadVideo (file) {
        let fileSize = file.size / 1024 / 1024 < 50;
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) == -1) {
          this.$message.error("请上传正确的视频格式");
          return false;
        }
        /* if (!fileSize) {
          this.$message.danger("视频大小不能超过50MB");
          return false;
        }
        */

      },
      // 上传成功回调
      uploadVideoSuccess (response, file, fileList, index) {
        if (response.code === '200') {
          // 状态码为200时则上传成功
          this.apparatusList[index].isShowUploadVideo = true;
          this.apparatusList[index].videoFlag = false;
          this.apparatusList[index].videoUploadPercent = 100;
          this.apparatusList[index].operateVideoUrl = file.response.object[0]

          this.$message.success('视频上传成功');
        } else {
          this.$message.error(response.Message);
          // 状态码不是200时上传失败 从列表中删除
          fileList.splice(fileList.indexOf(file), 1);
        }
      },
      //进度条
      uploadVideoProcess (event, file, fileList, index) {
        this.apparatusList[index].videoFlag = true;
        this.apparatusList[index].videoUploadPercent = Math.floor(event.percent);
      },
    },
    components: {
      'code-config': codeConfig,
      VueNeditorWrap
    }
  }
</script>

<style scoped lang="scss">
  .avatar-uploader /deep/.el-upload {
    border: none;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    &:hover {
      border-color: #409eff;
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px !important;
    height: 178px !important;
    line-height: 178px !important;
    text-align: center;
  }
  .avatar {
    width: 178px !important;
    height: 178px !important;
    display: block;
  }
</style>
